package com.djbx.points.common.client.utils;

import com.djbx.points.common.core.utils.ServiceResponse;

import java.lang.reflect.Proxy;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 〈〉
 *
 * @author sader
 * @date 2021/11/25
 * @since 1.0.0
 */
public abstract class DefaultFallbackFactory {

    private static ConcurrentHashMap<Class<?>, Object> map = new ConcurrentHashMap<>();
    /**
     * 获取默认的服务降级处理类
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getFallback(Class<T> clazz){
        T fallback = (T)map.get(clazz);
        if(fallback == null){
            fallback = (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, (proxy, method, args) -> {
                if(ServiceResponse.class.equals(method.getReturnType())){
                    return ServiceResponse.getServiceFallback();
                }
                return null;
            });
            map.put(clazz, fallback);
        }
        return fallback;
    }
}
